<template>
  <div class="contents">
    <TemplateCom>
      <!-- 搜索区域 -->
      <template #top>
        <el-form :model="searchForm" inline>
          <el-form-item label="姓名">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入姓名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="部门">
            <el-select
              v-model="searchForm.department"
              placeholder="请选择部门"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="dept in departments"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-select
              v-model="searchForm.role"
              placeholder="请选择角色"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="role in roles"
                :key="role.value"
                :label="role.label"
                :value="role.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </template>

      <!-- 按钮组 -->
      <template #action>
        <div class="button-group">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增人员
          </el-button>
          <el-button type="success" @click="handleBatchPermission">
            <el-icon><Key /></el-icon>
            批量权限绑定
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
      </template>

      <!-- 表格 -->
      <template #table>
        <el-table
          v-loading="loading"
          :data="filteredPersonnelList"
          stripe
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="role" label="角色" width="120" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="phone" label="电话" width="150" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="permissions" label="权限数量" width="100">
            <template #default="{ row }">
              <el-tag type="info">{{ row.permissions.length }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handlePermission(row)"
              >
                权限绑定
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 分页 -->
      <template #pagination>
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </template>
    </TemplateCom>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select
            v-model="formData.department"
            placeholder="请选择部门"
            style="width: 100%"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select
            v-model="formData.role"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roles"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限绑定对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限绑定"
      width="800px"
      @close="handlePermissionDialogClose"
    >
      <div class="permission-content">
        <div class="user-info">
          <h4>用户信息：{{ currentUser.name }} ({{ currentUser.username }})</h4>
        </div>
        <el-divider />
        <div class="permission-tree">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTreeData"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="currentUser.permissions"
            check-strictly
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePermissionSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus, Key, Delete } from "@element-plus/icons-vue";
import TemplateCom from "@/components/TemplateCom/index.vue";

// 响应式数据
const loading = ref(false);
const selectedRows = ref([]);
const dialogVisible = ref(false);
const permissionDialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const permissionTreeRef = ref();

// 搜索表单
const searchForm = reactive({
  name: "",
  department: "",
  role: ""
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表单数据
const formData = reactive({
  id: null,
  name: "",
  username: "",
  department: "",
  role: "",
  email: "",
  phone: "",
  status: "启用"
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  department: [{ required: true, message: "请选择部门", trigger: "change" }],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  phone: [{ required: true, message: "请输入电话", trigger: "blur" }]
};

// 当前操作用户
const currentUser = ref({});

// 部门选项
const departments = [
  { label: "技术部", value: "技术部" },
  { label: "产品部", value: "产品部" },
  { label: "运营部", value: "运营部" },
  { label: "人事部", value: "人事部" },
  { label: "财务部", value: "财务部" }
];

// 角色选项
const roles = [
  { label: "超级管理员", value: "super_admin" },
  { label: "管理员", value: "admin" },
  { label: "普通用户", value: "user" },
  { label: "访客", value: "guest" }
];

// 权限树配置
const treeProps = {
  children: "children",
  label: "title"
};

// 静态人员数据
const personnelList = ref([
  {
    id: 1,
    name: "张三",
    username: "zhangsan",
    department: "技术部",
    role: "admin",
    email: "zhangsan@example.com",
    phone: "13800138001",
    status: "启用",
    permissions: ["permission_page", "permission_button_router"],
    createTime: "2024-01-15 10:30:00"
  },
  {
    id: 2,
    name: "李四",
    username: "lisi",
    department: "产品部",
    role: "user",
    email: "lisi@example.com",
    phone: "13800138002",
    status: "启用",
    permissions: ["permission_page"],
    createTime: "2024-01-16 14:20:00"
  },
  {
    id: 3,
    name: "王五",
    username: "wangwu",
    department: "运营部",
    role: "user",
    email: "wangwu@example.com",
    phone: "13800138003",
    status: "禁用",
    permissions: [],
    createTime: "2024-01-17 09:15:00"
  },
  {
    id: 4,
    name: "赵六",
    username: "zhaoliu",
    department: "人事部",
    role: "admin",
    email: "zhaoliu@example.com",
    phone: "13800138004",
    status: "启用",
    permissions: [
      "permission_page",
      "permission_button_router",
      "permission_button_login"
    ],
    createTime: "2024-01-18 16:45:00"
  },
  {
    id: 5,
    name: "钱七",
    username: "qianqi",
    department: "财务部",
    role: "user",
    email: "qianqi@example.com",
    phone: "13800138005",
    status: "启用",
    permissions: ["permission_page"],
    createTime: "2024-01-19 11:30:00"
  },
  {
    id: 6,
    name: "钱七",
    username: "qianqi",
    department: "财务部",
    role: "user",
    email: "qianqi@example.com",
    phone: "13800138005",
    status: "启用",
    permissions: ["permission_page"],
    createTime: "2024-01-19 11:30:00"
  },
  {
    id: 7,
    name: "钱七",
    username: "qianqi",
    department: "财务部",
    role: "user",
    email: "qianqi@example.com",
    phone: "13800138005",
    status: "启用",
    permissions: ["permission_page"],
    createTime: "2024-01-19 11:30:00"
  },
  {
    id: 8,
    name: "钱七",
    username: "qianqi",
    department: "财务部",
    role: "user",
    email: "qianqi@example.com",
    phone: "13800138005",
    status: "启用",
    permissions: ["permission_page"],
    createTime: "2024-01-19 11:30:00"
  },
  {
    id: 9,
    name: "钱七",
    username: "qianqi",
    department: "财务部",
    role: "user",
    email: "qianqi@example.com",
    phone: "13800138005",
    status: "启用",
    permissions: ["permission_page"],
    createTime: "2024-01-19 11:30:00"
  }
]);

// 权限树数据
const permissionTreeData = ref([
  {
    id: "permission_page",
    title: "页面权限",
    children: [
      {
        id: "permission_page_index",
        title: "页面权限管理"
      }
    ]
  },
  {
    id: "permission_button",
    title: "按钮权限",
    children: [
      {
        id: "permission_button_router",
        title: "路由返回按钮权限"
      },
      {
        id: "permission_button_login",
        title: "登录接口返回按钮权限"
      }
    ]
  }
]);

// 计算属性
const filteredPersonnelList = computed(() => {
  let filtered = personnelList.value;

  if (searchForm.name) {
    filtered = filtered.filter(
      item =>
        item.name.includes(searchForm.name) ||
        item.username.includes(searchForm.name)
    );
  }

  if (searchForm.department) {
    filtered = filtered.filter(
      item => item.department === searchForm.department
    );
  }

  if (searchForm.role) {
    filtered = filtered.filter(item => item.role === searchForm.role);
  }

  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;

  return filtered.slice(start, end);
});

// 计算过滤后的总数
const filteredTotal = computed(() => {
  let filtered = personnelList.value;

  if (searchForm.name) {
    filtered = filtered.filter(
      item =>
        item.name.includes(searchForm.name) ||
        item.username.includes(searchForm.name)
    );
  }

  if (searchForm.department) {
    filtered = filtered.filter(
      item => item.department === searchForm.department
    );
  }

  if (searchForm.role) {
    filtered = filtered.filter(item => item.role === searchForm.role);
  }

  return filtered.length;
});

// 方法
const handleSearch = () => {
  pagination.currentPage = 1;
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    department: "",
    role: ""
  });
  pagination.currentPage = 1;
};

const handleSelectionChange = selection => {
  selectedRows.value = selection;
};

const handleAdd = () => {
  dialogTitle.value = "新增人员";
  Object.assign(formData, {
    id: null,
    name: "",
    username: "",
    department: "",
    role: "",
    email: "",
    phone: "",
    status: "启用"
  });
  dialogVisible.value = true;
};

const handleEdit = row => {
  dialogTitle.value = "编辑人员";
  Object.assign(formData, { ...row });
  dialogVisible.value = true;
};

const handleDelete = async row => {
  try {
    await ElMessageBox.confirm("确定要删除该人员吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const index = personnelList.value.findIndex(item => item.id === row.id);
    if (index > -1) {
      personnelList.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch {
    // 用户取消删除
  }
};

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个人员吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const selectedIds = selectedRows.value.map(row => row.id);
    personnelList.value = personnelList.value.filter(
      item => !selectedIds.includes(item.id)
    );
    selectedRows.value = [];
    ElMessage.success("批量删除成功");
  } catch {
    // 用户取消删除
  }
};

const handlePermission = row => {
  currentUser.value = { ...row };
  permissionDialogVisible.value = true;
};

const handleBatchPermission = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要绑定权限的人员");
    return;
  }
  ElMessage.info("批量权限绑定功能开发中...");
};

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (formData.id) {
        // 编辑
        const index = personnelList.value.findIndex(
          item => item.id === formData.id
        );
        if (index > -1) {
          personnelList.value[index] = { ...formData };
          ElMessage.success("编辑成功");
        }
      } else {
        // 新增
        const newId = Math.max(...personnelList.value.map(item => item.id)) + 1;
        personnelList.value.push({
          ...formData,
          id: newId,
          permissions: [],
          createTime: new Date().toLocaleString()
        });
        ElMessage.success("新增成功");
      }
      dialogVisible.value = false;
    }
  });
};

const handlePermissionSubmit = () => {
  const checkedKeys = permissionTreeRef.value.getCheckedKeys();
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys();
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];

  const index = personnelList.value.findIndex(
    item => item.id === currentUser.value.id
  );
  if (index > -1) {
    personnelList.value[index].permissions = allCheckedKeys;
    ElMessage.success("权限绑定成功");
  }
  permissionDialogVisible.value = false;
};

const handleDialogClose = () => {
  formRef.value?.resetFields();
};

const handlePermissionDialogClose = () => {
  currentUser.value = {};
};

const handleSizeChange = val => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
};

const handleCurrentChange = val => {
  pagination.currentPage = val;
};

// 生命周期
onMounted(() => {
  // 初始化完成
});
</script>

<style lang="scss" scoped>
.contents {
  width: 100%;
  height: calc(100vh - 84px);
}

.button-group {
  display: flex;
  gap: 10px;
}

.permission-content {
  .user-info {
    margin-bottom: 20px;

    h4 {
      margin: 0;
      color: #409eff;
    }
  }

  .permission-tree {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
  }
}
</style>
